package com.ivo.activiti.service;

import com.ivo.activiti.bpmn.ProcessService;
import com.ivo.activiti.entity.Diagram;
import com.ivo.activiti.entity.ProcessDiagram;
import com.ivo.activiti.repository.DiagramRepository;
import com.ivo.activiti.repository.ProcessDiagramRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author wj
 * @version 1.0
 */
@Service
public class ProcessDiagramService {

    @Resource
    private ProcessDiagramRepository processDiagramRepository;

    @Resource
    private DiagramRepository diagramRepository;

    @Resource
    private ProcessService processService;

    public List<ProcessDiagram> getProcessDiagram() {
        return processDiagramRepository.findAll();
    }

    public ProcessDiagram getProcessDiagram(long id) {
        return processDiagramRepository.findById(id).orElse(null);
    }

    public Diagram getDiagram(long diagramId) {
        return diagramRepository.findById(diagramId).orElse(null);
    }

    public void saveDiagram(Diagram diagram) {
        diagramRepository.save(diagram);
    }

    public void saveProcessDiagram(ProcessDiagram processDiagram) {
        processDiagramRepository.save(processDiagram);
    }

    public void deployProcessDiagram(long id) {
        ProcessDiagram processDiagram = getProcessDiagram(id);
        Diagram diagram = getDiagram(processDiagram.getDiagramId());
        processService.deploy(processDiagram.getBusinessKey()+".bpmn", diagram.getXml());
        processDiagram.setDeploy(true);
        processDiagram.setDeployDate(new Date());
        saveProcessDiagram(processDiagram);
    }
}
